<template>
  <el-dialog
    v-model="visible"
    title="催款记录导入向导"
    width="800px"
    @close="handleClose"
  >
    <el-steps :active="currentStep" finish-status="success" simple>
      <el-step title="上传文件" />
      <el-step title="映射字段" />
      <el-step title="预览数据" />
      <el-step title="导入完成" />
    </el-steps>
    
    <div class="step-content">
      <!-- 步骤1: 上传文件 -->
      <div v-show="currentStep === 0" class="step-panel">
        <el-upload
          ref="uploadRef"
          class="upload-demo"
          drag
          :auto-upload="false"
          :on-change="handleFileChange"
          :on-remove="handleFileRemove"
          accept=".xlsx,.xls,.csv"
        >
          <el-icon class="el-icon--upload"><upload-filled /></el-icon>
          <div class="el-upload__text">
            将文件拖到此处，或<em>点击上传</em>
          </div>
          <template #tip>
            <div class="el-upload__tip">
              请上传Excel或CSV格式的催款记录文件，文件大小不超过10MB
            </div>
          </template>
        </el-upload>
        
        <div class="template-download">
          <el-button type="primary" link @click="downloadTemplate">
            <el-icon><Download /></el-icon>下载导入模板
          </el-button>
        </div>
      </div>
      
      <!-- 步骤2: 映射字段 -->
      <div v-show="currentStep === 1" class="step-panel">
        <el-alert
          title="请将上传文件中的列映射到系统字段"
          type="info"
          show-icon
          style="margin-bottom: 20px;"
        />
        
        <el-table :data="columnMapping" border>
          <el-table-column prop="fileColumn" label="文件列名" width="200" />
          <el-table-column prop="systemField" label="系统字段">
            <template #default="{ row }">
              <el-select v-model="row.systemField" placeholder="请选择映射字段" style="width: 100%">
                <el-option
                  v-for="field in systemFields"
                  :key="field.value"
                  :label="field.label"
                  :value="field.value"
                />
              </el-select>
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      <!-- 步骤3: 预览数据 -->
      <div v-show="currentStep === 2" class="step-panel">
        <el-alert
          title="请检查导入数据，确认无误后点击导入"
          type="warning"
          show-icon
          style="margin-bottom: 20px;"
        />
        
        <el-table :data="previewData" height="300" border>
          <el-table-column
            v-for="column in previewColumns"
            :key="column.prop"
            :prop="column.prop"
            :label="column.label"
            :width="column.width"
          />
        </el-table>
        
        <div class="preview-stats">
          <span>总记录数: {{ previewData.length }}</span>
          <span>成功映射: {{ mappedCount }}</span>
          <span>映射失败: {{ unmappedCount }}</span>
        </div>
      </div>
      
      <!-- 步骤4: 导入完成 -->
      <div v-show="currentStep === 3" class="step-panel">
        <el-result
          icon="success"
          title="导入成功"
          :sub-title="`成功导入 ${importResult.successCount} 条催款记录，失败 ${importResult.failCount} 条`"
        >
          <template #extra>
            <el-button type="primary" @click="handleFinish">完成</el-button>
          </template>
        </el-result>
      </div>
    </div>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose" v-show="currentStep !== 3">取消</el-button>
        <el-button @click="handlePrev" v-show="currentStep > 0 && currentStep < 3">上一步</el-button>
        <el-button type="primary" @click="handleNext" v-show="currentStep < 2">下一步</el-button>
        <el-button type="primary" @click="handleImport" v-show="currentStep === 2">导入</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { UploadFilled, Download } from '@element-plus/icons-vue'
import type { UploadInstance, UploadFile, UploadRawFile } from 'element-plus'

interface ColumnMapping {
  fileColumn: string
  systemField: string
}

interface SystemField {
  label: string
  value: string
}

interface ImportResult {
  successCount: number
  failCount: number
  errors: string[]
}

interface Props {
  modelValue: boolean
}

const props = defineProps<Props>()

const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
  (e: 'import-success'): void
}>()

const visible = ref(false)
const currentStep = ref(0)
const uploadRef = ref<UploadInstance>()
const uploadedFile = ref<UploadFile | null>(null)
const columnMapping = ref<ColumnMapping[]>([])
const previewData = ref<any[]>([])
const previewColumns = ref<any[]>([])
const mappedCount = ref(0)
const unmappedCount = ref(0)
const importResult = ref<ImportResult>({
  successCount: 0,
  failCount: 0,
  errors: []
})

const systemFields: SystemField[] = [
  { label: '订单号', value: 'orderNo' },
  { label: '客户名称', value: 'customerName' },
  { label: '催款方式', value: 'collectionMethod' },
  { label: '催款结果', value: 'collectionResult' },
  { label: '催款日期', value: 'collectionDate' },
  { label: '联系人', value: 'contactPerson' },
  { label: '下次跟进日期', value: 'nextFollowupDate' },
  { label: '备注', value: 'notes' }
]

watch(
  () => props.modelValue,
  (newVal) => {
    visible.value = newVal
    if (!newVal) {
      // 重置状态
      currentStep.value = 0
      uploadedFile.value = null
      columnMapping.value = []
      previewData.value = []
      previewColumns.value = []
      mappedCount.value = 0
      unmappedCount.value = 0
      importResult.value = {
        successCount: 0,
        failCount: 0,
        errors: []
      }
    }
  }
)

watch(
  () => visible.value,
  (newVal) => {
    emit('update:modelValue', newVal)
  }
)

const handleFileChange = (uploadFile: UploadFile, fileList: UploadFile[]) => {
  uploadedFile.value = uploadFile
  // 模拟解析文件列
  columnMapping.value = [
    { fileColumn: '订单编号', systemField: '' },
    { fileColumn: '客户名称', systemField: '' },
    { fileColumn: '催款方式', systemField: '' },
    { fileColumn: '催款结果', systemField: '' },
    { fileColumn: '催款日期', systemField: '' }
  ]
}

const handleFileRemove = () => {
  uploadedFile.value = null
  columnMapping.value = []
}

const downloadTemplate = () => {
  ElMessage.info('下载模板功能开发中')
}

const handlePrev = () => {
  currentStep.value--
}

const handleNext = () => {
  if (currentStep.value === 0 && !uploadedFile.value) {
    ElMessage.warning('请先上传文件')
    return
  }
  
  if (currentStep.value === 1) {
    // 模拟预览数据
    previewData.value = [
      {
        orderNo: 'PO2023001',
        customerName: '测试客户A',
        collectionMethod: '电话',
        collectionResult: '已联系客户',
        collectionDate: '2023-03-01'
      },
      {
        orderNo: 'PO2023002',
        customerName: '测试客户B',
        collectionMethod: '邮件',
        collectionResult: '发送催款邮件',
        collectionDate: '2023-03-02'
      }
    ]
    
    previewColumns.value = [
      { prop: 'orderNo', label: '订单号', width: 150 },
      { prop: 'customerName', label: '客户名称', width: 150 },
      { prop: 'collectionMethod', label: '催款方式', width: 120 },
      { prop: 'collectionResult', label: '催款结果' },
      { prop: 'collectionDate', label: '催款日期', width: 120 }
    ]
    
    mappedCount.value = 2
    unmappedCount.value = 0
  }
  
  currentStep.value++
}

const handleImport = () => {
  // 模拟导入过程
  importResult.value = {
    successCount: 2,
    failCount: 0,
    errors: []
  }
  currentStep.value++
}

const handleFinish = () => {
  emit('import-success')
  handleClose()
}

const handleClose = () => {
  visible.value = false
}
</script>

<style scoped lang="scss">
.step-content {
  margin: 20px 0;
  min-height: 300px;
}

.step-panel {
  padding: 20px 0;
}

.template-download {
  text-align: center;
  margin-top: 20px;
}

.preview-stats {
  display: flex;
  justify-content: space-between;
  margin-top: 16px;
  padding: 12px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>